package com.course.app.api.controller;

import com.course.app.biz.AuthBiz;
import com.course.app.biz.UserBiz;
import com.course.domain.enums.Role;
import com.course.domain.model.Account;
import com.course.domain.model.Student;
import com.course.domain.model.Teacher;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by Justin on 2017/5/30.
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    private final AuthBiz authBiz;
    private final UserBiz userBiz;

    @Autowired
    public AuthController(AuthBiz authBiz, UserBiz userBiz) {
        this.authBiz = authBiz;
        this.userBiz = userBiz;
    }

    @PostMapping("/login")
    public AuthResponse login(@RequestBody AuthRequest auth) {
        String username = auth.getUsername();
        String password = auth.getPassword();
        AuthResponse response = new AuthResponse();
        try {
            Account account = userBiz.loadAccountByUsername(username);
            if (account != null) {
                response.setSuccess(true);
                switch (account.getRole()) {
                    case STUDENT:
                        Student student = userBiz.loadStudentByAccount(account.getId());
                        response.setRole(Role.STUDENT);
                        response.setUserId(student.getId());
                        break;
                    case TEACHER:
                        Teacher teacher = userBiz.loadTeacherByAccount(account.getId());
                        response.setRole(Role.TEACHER);
                        response.setUserId(teacher.getId());
                        break;
                    case ADMIN:
                        response.setRole(Role.ADMIN);
                        response.setUserId(account.getId());
                        break;
                }
                String token = authBiz.login(username, password);
                response.setToken(token);
            }
        } catch (Exception e) {
            response.setSuccess(false);
            response.setError(e.toString());
        }

        return response;
    }

    @Data
    private static class AuthRequest {
        private String username;
        private String password;
    }

    @Data
    private static class AuthResponse {
        private boolean success;
        private String token;
        private String error;
        private Role role;
        private int userId;
    }
}